<!--
 * @Author: lihaogn
 * @Date: 2021-12-26 15:03:23
 * @LastEditTime: 2021-12-26 16:01:57
 * @LastEditor: lihaogn
 * @Description: 表格工具，通过选择动态显示列
 * @FilePath: \lix-admin-vue2\src\components\common\lix-table-select-column\index.vue
-->
<template>
  <el-popover placement="bottom-end" trigger="click">
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <el-divider></el-divider>
    <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
      <el-checkbox
        v-for="item in columns"
        :key="item.prop"
        :label="item.prop"
        >{{ item.label }}</el-checkbox
      >
    </el-checkbox-group>
    <el-button
      slot="reference"
      icon="el-icon-more"
      :size="size"
      style="margin-left:10px;"
    ></el-button>
  </el-popover>
</template>

<script>
export default {
  props: {
    /**
     * 表格列
     * [{ label:'', prop:''}, ...]
     */
    columns: {
      type: Array,
      required: true
    },
    // 按钮的尺寸
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      checkList: this.columns.map(x => x.prop),
      checkAll: true,
      // 是否半选
      isIndeterminate: false
    }
  },
  created() {
    this.$emit('change', this.columns)
  },
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2021-12-26 16:00:02
     * @description: 全选事件
     * @param {*} val:Boolean - 是否全选了
     * @return {*}
     */
    handleCheckAllChange(val) {
      this.checkList = val ? this.columns.map(x => x.prop) : []
      this.isIndeterminate = false
      this.$emit('change', val ? this.columns : [])
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-26 16:00:21
     * @description: 选择事件
     * @param {*} val:Array - 选择到的数据
     * @return {*}
     */
    handleCheckedChange(val) {
      let checkedCount = val.length
      this.checkAll = checkedCount === this.columns.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.columns.length
      this.$emit(
        'change',
        this.columns.filter(item => val.includes(item.prop))
      )
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  display: block;
}

.el-divider {
  margin: 8px 0;
}
</style>
